/*
 * header file for some extra C functions in Linux terminals
 *
 *	-gotoxy(int,int);			usual gotoxy method, known from pascal
 *	-clearscr();				clears the screen
 *	-textcolor(COLOR);			changes the text color in terminal
 *								supported: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE
 *	-backgroundcolor(COLOR)		changes the background color in terminal
 *								supported: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE
 *	-defaultcolors();			sets both text and background colors to their defaults
 *	-getcharacter();			get PRESSED key value, Enter key is not needed
 *
 * author: László Ádám
 * e-mail: adam.laszlo.91@gmail.com
 * 2014. 1. august
 * version: 1.4
 */

#ifndef linuxstuff_h
#define linuxstuff_h

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

#define BLACK 0
#define RED 1
#define GREEN 2
#define YELLOW 3
#define BLUE 4
#define MAGENTA 5
#define CYAN 6
#define WHITE 7

//  itoa  //
char litoa(int i) {
	return i + '0';
}

//  getch  //
int lgetch(void) {
	struct termios oldt, newt;
	int c;
	tcgetattr( STDIN_FILENO, &oldt);
	newt = oldt;
	newt.c_lflag &= ~( ICANON | ECHO);
	tcsetattr( STDIN_FILENO, TCSANOW, &newt);
	c = getchar();
	tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
	return c;
}

//  textcolor  //
void textcolor(int color) {
	switch (color) {
	case RED:
		printf("%s", "\033[31m");
		break;
	case GREEN:
		printf("%s", "\033[32m");
		break;
	case YELLOW:
		printf("%s", "\033[33m");
		break;
	case BLUE:
		printf("%s", "\033[34m");
		break;
	case MAGENTA:
		printf("%s", "\033[35m");
		break;
	case CYAN:
		printf("%s", "\033[36m");
		break;
	case WHITE:
		printf("%s", "\033[37m");
		break;
	default:
		printf("%s", "\033[30m");
		break;
	}
}

//  backgroundcolor  //
void backgroundcolor(char color) {
	switch (color) {
	case RED:
		printf("%s", "\033[41m");
		break;
	case GREEN:
		printf("%s", "\033[42m");
		break;
	case YELLOW:
		printf("%s", "\033[43m");
		break;
	case BLUE:
		printf("%s", "\033[44m");
		break;
	case MAGENTA:
		printf("%s", "\033[45m");
		break;
	case CYAN:
		printf("%s", "\033[46m");
		break;
	case WHITE:
		printf("%s", "\033[47m");
		break;
	default:
		printf("%s", "\033[40m");
		break;
	}
}

//  defaultcolors  //
void defaultcolors() {
	printf("%s", "\033[0m");
}

//  gotoxy  //
void gotoxy(int x, int y) {
	char string[8];
	char tempx[2];
	char tempy[2];
	char tens, ones;

	tens = x / 10;
	ones = x % 10;
	tempx[0] = litoa(tens);
	tempx[1] = litoa(ones);
	tens = y / 10;
	ones = y % 10;
	tempy[0] = litoa(tens);
	tempy[1] = litoa(ones);

	string[0] = '\033';
	string[1] = '[';
	string[2] = tempy[0];
	string[3] = tempy[1];
	string[4] = ';';
	string[5] = tempx[0];
	string[6] = tempx[1];
	string[7] = 'H';
	printf("%s", string);
}

//  clearscr  //
void clearscr() {
	printf("\e[1;1H\e[2J");
}

#endif

